package org.example.c2;

import lombok.extern.slf4j.Slf4j;
import org.openjdk.jol.info.ClassLayout;

/**
 * @author liu-rui
 * @date 2020/6/2 上午11:06
 * @description 实践:偏向锁批量重定向
 * 　-XX:BiasedLockingStartupDelay=0　-XX:BiasedLockingBulkRebiasThreshold=2
 * 为了便于测试，关闭延迟，批量重定向阈值为2
 * @since
 */
@Slf4j
public class Demo12 {
    public static void main(String[] args) throws InterruptedException {
        Object[] locks = createLocks(20);
        testRebias(locks, 1, 1);
    }

    private static Object[] createLocks(int num) throws InterruptedException {
        Object[] locks = new Object[num];

        final Thread thread = new Thread(() -> {
            for (int i = 0; i < locks.length; i++) {
                locks[i] = new Object();

                synchronized (locks[i]) {
                }
                log.info("初始化偏向锁　{}", i);
                System.out.println(ClassLayout.parseInstance(locks[i]).toPrintable());
            }
        });

        thread.start();
        thread.join();

        return locks;
    }

    private static void testRebias(Object[] locks, int stage, int n) throws InterruptedException {
        for (int s = 0; s < stage; s++) {
            int finalS = s;
            final Thread thread = new Thread(() -> {
                for (int j = 0; j < n; j++) {
                    System.out.println("\n\n\n");
                    log.info("第{} {}波", finalS + 1, j + 1);

                    for (int i = 0; i < locks.length; i++) {
                        synchronized (locks[i]) {
                            log.info("中　{}", i);
                            System.out.println(ClassLayout.parseInstance(locks[i]).toPrintable());
                        }
                        log.info("后面　{}", i);
                        System.out.println(ClassLayout.parseInstance(locks[i]).toPrintable());
                    }
                }
            });

            thread.start();
            thread.join();
        }
    }
}
